package goodenglish.infrastructure.repository.db;

import goodenglish.domain.model.profword.ProfWordLib;
import goodenglish.domain.model.profword.ProfWordLibRepository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * 熟词库资源库
 * 
 * @author qiuriyuchen E-mail:panpan_001@126.com
 */
public class ProfWordLibRepositoryDb implements ProfWordLibRepository {
	@Override
	public ProfWordLib getProfWordLib() {
		ProfWordLib profWords = new ProfWordLib();
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = DBUtil.getConnection();
			stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery("select spell from ProfWord;");
			while (rs.next()) {
				System.out.println("spell = " + rs.getString("spell"));
				profWords.addProfWord(rs.getString("spell"));
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtil.closeStatement(stmt);
			DBUtil.closeConnection(conn);
		}
		return profWords;
	}

	@Override
	public void addOrUpdateProfWordLib(ProfWordLib profWords) {
		Connection conn = null;
		PreparedStatement prep = null;
		Statement stmt = null;
		try {
			conn = DBUtil.getConnection();
			stmt = conn.createStatement();
			stmt.executeUpdate("delete from ProfWord");
			prep = conn.prepareStatement("insert into ProfWord(spell) values (?);");
			for (String spell : profWords.getWords()) {
				prep.setString(1, spell);
				prep.addBatch();
			}
			conn.setAutoCommit(false);
			prep.executeBatch();
			conn.setAutoCommit(true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtil.closeStatement(stmt, prep);
			DBUtil.closeConnection(conn);
		}

	}
}
